import React, {Component} from 'react';
import {Dropdown,Input,Cascader,message,Select} from 'antd';
import { DownOutlined,CloseCircleOutlined } from '@ant-design/icons';
import config from 'src/commons/config-hoc';
import Map from 'ol/Map';
import View from 'ol/View';
import LayerVector from 'ol/layer/Vector';
import TileImage from 'ol/source/TileImage';
import SourceVector from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import Text from 'ol/style/Text';
import { defaults } from 'ol/control';
import 'ol/ol.css';
import { Fill, Stroke, Style, Icon, Circle as CircleStyle } from 'ol/style';
import {Image,Tile as TileLayer, Vector as VectorLayer,Heatmap} from 'ol/layer';
import { fromLonLat, transform ,transformExtent,toLonLat} from 'ol/proj';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import styles from './styles.less';
import { OSM,ImageStatic, Vector as VectorSource } from 'ol/source';
import { LineString, Polygon } from 'ol/geom';
import { getArea, getLength,getDistance } from 'ol/sphere';
import { unByKey } from 'ol/Observable';
import Overlay from 'ol/Overlay';
import Draw, { createBox, createRegularPolygon, } from 'ol/interaction/Draw';
import Cluster from 'ol/source/Cluster';
import XYZ from 'ol/source/XYZ';
import { Modify } from 'ol/interaction';
import BusRoute from './BusRoute';
import BusNav from './BusNav';
import Popup from "../../components/map/ol-popup";
let selectData = ['香港仔運動場(近香葉道)','香港基督教會活石堂(香港堂) ','香港浸信會聯會香港西北扶輪社幼稚園 ','香港福州語福音佈道會香港堂 ','香港警務處香港仔分區警署 ','香港警務處香港仔分區警署赤柱分署 '];

const { Option } = Select;
const defaultCenterLocation = [114.16546,22.27534];
const defaultZoom = 13;
const options = [
    {
        value: 'hk',
        label: '香港',
        children: [
            {
                value: 'gangdaonanqu',
                label: '港岛南区',
            },
            {
                value: 'zhongxiqu',
                label: '中西区',
            },
            {
                value: 'zhongxiqu',
                label: '湾仔',
            },
        ],
    },
    {
        value: 'xinjie',
        label: '新界',
        children: [
            {
                value: 'kuiqing',
                label: '葵青',
            },
        ],
    },
    {
        value: 'jiulong',
        label: '九龙',
        children: [
            {
                value: 'nanjing',
                label: '深水埗',
            },
        ],
    },
];
@config({
    title: '地图',
    path: '/kmb-search',
    noFrame: true,
    noAuth: true,
})
export default class index extends Component {
    state = {
        mapCenter: defaultCenterLocation,
        zoom: defaultZoom,
        dataSource:[],
        startpointOption:[]
    };
    componentDidMount() {
        setTimeout(()=>{
            this.mapInitLoad();
        },300)
        this.handleSubmit();
    }
    handleSubmit = ()=> {
        this.props.ajax.get('/api/list')
            .then(res => {
                const dataSource = res?.data || [];
                this.setState({ dataSource });
            })
    };
    mapInitLoad=()=>{
        const { mapCenter,zoom } = this.state;

        this.map_layer = new TileLayer({
            visible: true,
            source: new XYZ({
                url: 'http://www.google.cn/maps/vt?lyrs=r@189&gl=cn&x={x}&y={y}&z={z}'
            })
        });
        this.raster = new TileLayer({
            source: new OSM(),
        });

        this.pointSourceVector = new SourceVector();
        this.point_layer = new LayerVector({
            source: this.pointSourceVector,
            overlaps: false,
            wrapX: false,
            zIndex:10,
        })

        this.map_view = new View({
            projection: 'EPSG:4326',
            center: mapCenter,
            zoom: zoom,
        })

        //7、创建地图组件
        this.map = new Map({
            view: this.map_view,
            layers: [
                this.raster,
                this.map_layer,
                this.point_layer,
            ],
            controls: defaults({
                // attributionOptions: ({
                //     collapsible: false
                // }),
                // //清除地图上默认样式（放大、缩小、旋转按钮等）
                attribution: false,
                rotate: false,
                zoom: false
            }),
            target: this.mapDom
        });

        this.map.on("click",  (e)=> {
            //要素选中事件，获取选中要素信息
            this.map.forEachFeatureAtPixel(e.pixel,  (feature)=> {
                console.log(feature.values_,"feature");
                let values = feature.values_;
                console.log(e.coordinate,values,"===============");
                if(!values.data) return false;
                this.mapPopup(e.coordinate,values);
                return feature;
            });

        });
        this.map.on("moveend",(e)=>{
            let zoom = this.map.getView().getZoom();
            console.log(zoom,"zoom");
        });

    }

    addVectorPoint =( options)=> {
        //添加矢量要素点
        this.newFeature = new Feature({
            data: options.data,
            geometry: new Point(options.location),
            datatype:options.options
        });
        let url = options.icon?options.icon:require('./image/stopcircle.png');
        //图标样式
        let iconStyle = new Style({
            image: new Icon(
                /** @type {olx.style.IconOptions} */ ({
                    anchor: [0.5, 1],
                    anchorXUnits: "fraction",
                    anchorYUnits: "pixels",
                    src: url,
                    // scale: datatype==='weather'?0.1:1
                })
            ),

        });

        this.newFeature.setStyle(iconStyle);

        //清除矢量图层里的所有要素
        // layer.getSource().clear();

        //将当前要素添加到矢量数据源中
        this.point_layer.getSource().addFeature(this.newFeature);
        this.point_layer.setVisible(true);

    }

    /**
     * 加载线
     * @returns {boolean}
     */
    loadLineFeature = (location,color,lineDash)=>{
        // if(this.atmosphereLayer){
        //     this.map.removeLayer(this.atmosphereLayer);
        //     this.atmosphereLayer = null;
        //     return false;
        // }
        this.lineFeature = new Feature(
            new LineString(location)
        );
        let iconStyle = new Style({
            stroke: new Stroke({
                width: 5,
                color: color?color:'#0D21A1',
                lineDash: lineDash?[10, 10, 10]:[]
            }),
        });

        this.lineFeature.setStyle(iconStyle);
        this.point_layer.getSource().addFeature(this.lineFeature);
    }

    /**
     * Popup
     */
    mapPopup = (coordinate,values={})=>{
        this.setState({
            locationInfo : values.data,
        })
        this.Popup = new Popup({ map:this.map });
        this.map.addOverlay(this.Popup);
        this.Popup.show(coordinate,this.popup);
    }

    mapPopupClose = ()=> {
        this.Popup && this.Popup.hide();
    };

    /**
     * 设置 center坐标 zoom
     */
    handleSetMapView = (options) =>{
        const {mapCenter,zoom} = this.state;
        options && this.map_view.animate({
            center: options.location?options.location:mapCenter,
            zoom: options.zoom?options.zoom:zoom,
            duration: 1000
        });
    }

    /**
     * 设置 zoom 放大缩小  +1 -1
     */
    setMapZoom = (zoom)=> {
        this.map_view.animate({
            zoom: this.map_view.getZoom() +zoom,
            duration: 500
        });
    }
    /*
  *清空坐标点
  */
    clearPointn=()=> {
        if(this.point_layer) this.point_layer.getSource().clear();
    }

    handleVisibleBusroute = flag => {
        this.setState({ visibleBusroute: flag ,busName:''});
    };
    handleVisibleBusnav = flag => {
        this.setState({ visibleBusnav: flag });
    };
    onChangeInputStart = (value) => {
        this.setState({
            startLocationText: value,
        });
    };
    onChangeCascaderStart = (value, selectedOptions) => {
        this.setState({
            startLocationText: selectedOptions.map(o => o.label).join(', '),
        });
    };
    onChangeInputEnd = (value) => {
        this.setState({
            endLocationText: value,
        });
    };
    onChangeCascaderEnd = (value, selectedOptions) => {
        this.setState({
            endLocationText: selectedOptions.map(o => o.label).join(', '),
        });
    };
    handleLocationTransform = ()=>{
        const {startLocationText,endLocationText} = this.state;
        this.setState({
            startLocationText: endLocationText,
            endLocationText: startLocationText,
        });
    }
    handleBusrouteSearch = ()=>{
        const {busName,dataSource} = this.state;
        let flag = false;
        let data = null;
        if(!busName){
            message.warning('輸入巴士路線號碼');
            return false;
        }
        for (let i = 0; i <dataSource.length ; i++) {
            if(dataSource[i].name ===busName){
                flag = true;
                data = dataSource[i]
                break;
            }
        }
        if(!flag){
            message.warning('未査詢到當前巴士');
            return false;
        }
        this.clearPointn();
        // let data = this.state.dataSource[0].children;
        let list = [];
        data&&data.children.forEach((item,index)=>{
            let location = item.location.split(',');
            let location3857 = transform(location,'EPSG:4326', 'EPSG:3857' );
            location = transform(location3857, 'EPSG:3857','EPSG:4326' )
            let icon =''
            if(index===0){
                icon = require('./image/map_start.png')
            }else if(index===data.children.length-1){
                icon = require('./image/map_end.png')
            }
            this.addVectorPoint({data:item,location,icon})
            list.push(location)
        })
        this.loadLineFeature(data.path?data.path:list)
        this.setState({VisibleBusRoute:true,visibleBusroute:false,itemData:data})
    }
    handleBusNavSearch = ()=>{
        this.clearPointn();
        this.setState({VisibleBusNav:true,visibleBusnav:false})
    }
    handleBusNav = ()=>{
        let dataSource = this.state.dataSource;
        let data1 = [];
        let data2 = [];
        dataSource.forEach(item=>{
            if(item.name=='17'){
                data1 = item
            }else if (item.name=='2'){
                data2 = item
            }
        })
        let list1 = [];
        let transit1 = '',transit2='';
        if(data1.path)list1 = data1.path.filter((item,index)=>index<16);
        data1.children&&data1.children.forEach((item,index)=>{
            if(index>8) return false;
            let location = item.location.split(',');
            let location3857 = transform(location,'EPSG:4326', 'EPSG:3857' );
            location = transform(location3857, 'EPSG:3857','EPSG:4326' )
            let icon =''
            if(index===0){
                icon = require('./image/map_start_point.png')
            }else if(index===8){
                icon = require('./image/map_p2p_bus-stop.png');
                transit1 = location;
            }
            this.addVectorPoint({data:item,location,icon})
            if(!data1.path)list1.push(location)
        })
        let list2 = [];
        if(data2.path)list2 = data2.path;
        data2.children&&data2.children.forEach((item,index)=>{
            if(index>4){
                let location = item.location.split(',');
                let location3857 = transform(location,'EPSG:4326', 'EPSG:3857' );
                location = transform(location3857, 'EPSG:3857','EPSG:4326' )
                let icon =''
                if(index===5){
                    icon = require('./image/map_p2p_bus-stop.png')
                    transit2 = location;
                }else if(index===data2.children.length-1){
                    icon = require('./image/map_end_point.png')
                }
                this.addVectorPoint({data:item,location,icon})
                // list2.push(location)
                if(!data2.path)list2.push(location)
            }
        })
        console.log(list1,"=========");
        this.loadLineFeature(list1)
        this.loadLineFeature(list2,'#009900')
        this.loadLineFeature([transit1,transit2],'#000',true)
    }
    showAllBusStation = ()=>{
        this.clearPointn();
        const {dataSource,showAllBusStation} = this.state;
        !showAllBusStation&&dataSource.forEach(m=>{
            m.children.forEach(n=>{
                let location = n.location.split(',');
                this.addVectorPoint({data:n,location})
            })
        })
        this.setState({showAllBusStation:!showAllBusStation})
    }

    handleSearchS = value => {
        if (value) {
            let arr =[];
            selectData.forEach(item=>{
                if(item.indexOf(value)>-1){
                    arr.push(item)
                }
            })
            this.setState({ startpointOption :arr,startLocationText:value})

        } else {
            this.setState({ startpointOption: [] });
        }
    };
    handleSearchE = value => {
        if (value) {
            let arr =[];
            selectData.forEach(item=>{
                if(item.indexOf(value)>-1){
                    arr.push(item)
                }
            })
            this.setState({ startpointOption :arr,endLocationText:value})

        } else {
            this.setState({ startpointOption: [] });
        }
    };
    onClear = (value)=>{
        console.log(value,"========");
    }
    render() {
        const {
            dataSource,
            visibleBusroute,
            visibleBusnav,
            startLocationText,
            endLocationText,
            VisibleBusRoute,
            VisibleBusNav,
            busName,
            locationInfo,
            itemData
        } = this.state;
        const busrouteSearch = (
            <div className={styles.busrouteSearch}>
                <h1>巴士路線</h1>
                <div className={styles.searchInput}>
                    <img src={require('./image/bus_icon.png')} alt=""/>
                    <Input placeholder="輸入巴士路線號碼" bordered={false} value={busName} onChange={(e)=>this.setState({busName:e.target.value})} />
                </div>
                <div className={styles.btnSearch} onClick={()=>this.handleBusrouteSearch()}>搜尋</div>
            </div>
        );
        const busnavSearch = (
            <div className={styles.busnavSearch}>
                <h1>點對點</h1>
                <div className={styles.searchInput}>
                    <div>
                        <div className={styles.inputWrap}>
                            {/*<Input  value={startLocationText} bordered={false} onChange={this.onChangeInputStart} />*/}
                            <Select
                                showSearch
                                value={startLocationText}
                                placeholder="輸入 起點 或點擊地圖"
                                defaultActiveFirstOption={false}
                                showArrow={false}
                                filterOption={false}
                                onSearch={this.handleSearchS}
                                onChange={this.onChangeInputStart}
                                notFoundContent={null}
                            >
                                {this.state.startpointOption.map(d => <Option key={d}>{d}</Option>)}
                            </Select>
                            <Cascader options={options} onChange={this.onChangeCascaderStart}>
                                <DownOutlined style={{color:'#369CA3',fontSize:18}} />
                            </Cascader>
                        </div>
                        <div className={styles.inputWrap}>
                            <Select
                                showSearch
                                value={endLocationText}
                                placeholder="輸入 終點 或點擊地圖"
                                defaultActiveFirstOption={false}
                                showArrow={false}
                                filterOption={false}
                                onSearch={this.handleSearchE}
                                onChange={this.onChangeInputEnd}
                                notFoundContent={null}
                            >
                                {this.state.startpointOption.map(d => <Option key={d}>{d}</Option>)}
                            </Select>
                            <Cascader options={options} onChange={this.onChangeCascaderEnd}>
                                <DownOutlined style={{color:'#369CA3',fontSize:18}} />
                            </Cascader>
                        </div>
                    </div>
                    <img className={styles.transform} onClick={()=>this.handleLocationTransform()} src={require('./image/p2pExchange.png')} alt=""/>
                </div>
                <div className={styles.btnSearch} onClick={()=>this.handleBusNavSearch()} >搜尋</div>
            </div>
        );
        // console.log(itemData,"===33333");
        return (
            <div className={styles.main}>
                <div className={styles.header}>
                    <div className={styles.headerLeft}>
                        <Dropdown
                            overlay={busnavSearch}
                            placement="bottomLeft"
                            trigger="click"
                            arrow
                            onVisibleChange={this.handleVisibleBusnav}
                            visible={visibleBusnav}
                        >
                            <img src={require('./image/p2psearch.png')} alt=""/>
                        </Dropdown>
                        <Dropdown
                            overlay={busrouteSearch}
                            placement="bottomLeft"
                            trigger="click"
                            arrow
                            onVisibleChange={this.handleVisibleBusroute}
                            visible={visibleBusroute}
                        >
                            <img src={require('./image/routesearch.png')} alt=""/>
                        </Dropdown>
                    </div>
                    <ul className={styles.headerRight}>
                        <li>ENG</li>
                        <li>繁</li>
                        <li>簡</li>
                        <li>|</li>
                        <li>A</li>
                        <li style={{fontSize:20}}>A</li>
                        <li style={{fontSize:24}}>A</li>
                    </ul>
                </div>
                <div id="map" ref={ref =>this.mapDom = ref} className={styles.olmap}>
                    <BusRoute data={dataSource} value={busName} visible={VisibleBusRoute} onClose={()=>this.setState({VisibleBusRoute:!VisibleBusRoute})}/>
                    <BusNav data={dataSource} handleBusNav={this.handleBusNav} visible={VisibleBusNav} onClose={()=>this.setState({VisibleBusNav:!VisibleBusNav})}/>
                    <ul className={styles.mapTool}>
                        <li onClick={()=>this.handleSetMapView({location:defaultCenterLocation,zoom:defaultZoom})}>当前位置</li>
                        <li onClick={()=>this.setMapZoom(1)}>+</li>
                        <li onClick={()=>this.setMapZoom(-1)}>-</li>
                        <li onClick={()=>this.handleSetMapView({location:defaultCenterLocation,zoom:defaultZoom})}>初始位置</li>
                        <li onClick={()=>this.showAllBusStation()}>5</li>
                    </ul>
                </div>
                <div ref={ref=>this.popup =ref} className={styles.olPopup}>
                    {
                        locationInfo&&<div>
                            <div className={styles.popupHeader}>
                                <span>{itemData&&itemData.name} 往 {itemData&&itemData.children[itemData.children.length-1].busstop}</span>
                                <CloseCircleOutlined onClick={()=>this.mapPopupClose()} style={{color:'#919191',cursor: 'pointer'}} />
                            </div>
                            <div className={styles.content}>
                                <h3>{locationInfo.busstop}</h3>
                                <div>東頭村道東頭偉東樓外</div>
                                <ul>
                                    <li>到站時間</li>
                                    <li>
                                        15 分鐘   預定班次
                                    </li>
                                    <li>
                                        30 分鐘   預定班次
                                    </li>
                                </ul>
                                <div>途經此站的巴士路線:</div>
                                <div>1，17</div>
                            </div>
                        </div>
                    }
                </div>
            </div>
        );
    }
}
